package com.itheima.request;

import com.itheima.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

@WebServlet("/request/demo03")
public class ServletDemo03 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Map<String, String[]> map = req.getParameterMap();
        //key  value
        Student stu = new Student();

        map.forEach((k, v) -> {
            Class<? extends Student> clazz = stu.getClass();
            Field f = null;
            try {
                f = clazz.getDeclaredField(k);
                f.setAccessible(true);
                if(v.length>1){
                    f.set(stu,(Object) v);
                }else {
                    Class<?> type = f.getType();
                    if(type==int.class){
                        f.set(stu,Integer.parseInt(v[0]));
                    }else {
                        f.set(stu,v[0]);
                    }

                }

            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        });
        System.out.println(stu);

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
